package com.lmbsvn.core.util;

import org.apache.shiro.crypto.hash.Md5Hash;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class EncryptUtils {
	
	/**
	 * MD5加密
	 * @param source
	 * @return
	 */
	public static final String encryptMD5(String source) {
		if (source == null) {
			source = "";
		}
		Md5Hash md5 = new Md5Hash(source);
		return md5.toString();
	}
	
	/** 
     * 对密码进行md5加密,并返回密文和salt，包含在User对象中
     * @param password 密码 
     * @return 密文和salt 
     */ 
    public static String md5Password(String password, String salt){
    	return new Md5Hash(password,salt,2).toHex();
    }

	/**
	 * Apache SHA1加密
	 * @param str 明文
	 * @return 密文
	 */
	public static String encriptSHA1(String str) {
		try {
			return new sun.misc.BASE64Encoder().encode(MessageDigest.getInstance("SHA1").digest(str.getBytes()));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	private static final String cvt = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789#@$";
	private static final int fillchar = '*';

	/**
	 * 解密
	 * @param str 密文
	 * @return 明文
	 */
	public static String decrypt(String str) {
		byte[] data = str.getBytes();
		int c, c1;
		int len = data.length;
		StringBuffer ret = new StringBuffer((len * 3) / 4);
		for (int i = 0; i < len; ++i) {
			c = cvt.indexOf(data[i]);
			++i;
			c1 = cvt.indexOf(data[i]);
			c = ((c << 2) | ((c1 >> 4) & 0x3));
			ret.append((char) c);
			if (++i < len) {
				c = data[i];
				if (fillchar == c) {
					break;
				}
				c = cvt.indexOf((char) c);
				c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
				ret.append((char) c1);
			}
			if (++i < len) {
				c1 = data[i];
				if (fillchar == c1) {
					break;
				}
				c1 = cvt.indexOf((char) c1);
				c = ((c << 6) & 0xc0) | c1;
				ret.append((char) c);
			}
		}
		return ret.toString();
	}

}
